<template>
  <div class="member-management">
    <ReCommonTable
      ref="tableRef"
      :title="title"
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :search-fields="searchFields"
      :pagination="pagination"
      :show-summary="true"
      sum-text="汇总："
      :summary-method="getSummaries"
      @search="handleSearch"
      @refresh="handleRefresh"
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      @selection-change="handleSelectionChange"
    >
      <template #toolbar-add>
        <el-radio-group
          v-model="tabPosition"
          size="small"
          class="toolbar-radio-group"
        >
          <el-radio-button
            label="当日上钟"
            value="day"
            @click="() => handleTimeRangeClick('day')"
          />
          <el-radio-button
            label="当月上钟"
            value="month"
            @click="() => handleTimeRangeClick('month')"
          />
        </el-radio-group>
      </template>
      <!-- 操作列 -->
      <template #action="{ row }: any">
        <el-button size="small" @click="handleViewDetail(row)">
          查看
        </el-button>
      </template>
    </ReCommonTable>

    <!-- 上钟详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="上钟详情"
      width="90%"
      :close-on-click-modal="false"
    >
      <el-table
        v-loading="detailLoading"
        :data="detailTableData"
        border
        stripe
        max-height="500"
      >
        <el-table-column prop="l_no" label="订单编号" width="150" />
        <el-table-column
          prop="l_pname"
          label="项目名称"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="jname" label="技师名" width="100" />
        <el-table-column prop="l_mname" label="客户名称" width="120" />
        <el-table-column prop="l_yydate" label="预约日期" width="160" />
        <el-table-column
          prop="project_time"
          label="服务时长"
          width="100"
          align="right"
        />
        <el-table-column
          prop="shouprice"
          label="收款金额"
          width="120"
          align="right"
        />
        <el-table-column
          prop="tichengprice"
          label="提成"
          width="120"
          align="right"
        />
      </el-table>

      <!-- 详情分页 -->
      <div class="mt-4 flex justify-end">
        <el-pagination
          v-model:current-page="detailPagination.current"
          v-model:page-size="detailPagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="detailPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleDetailSizeChange"
          @current-change="handleDetailCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { ReCommonTable } from "@/components/ReCommonTable";
import type {
  SearchField,
  TableColumn
} from "@/components/ReCommonTable/src/index.vue";
import {
  getClockSituationList,
  getClockSituationDetails,
  type ClockSituationParams,
  type ClockSituationDetailParams,
  type ClockSituation
} from "@/api/order";
import { getEmployeeList, type Employee } from "@/api/employee";

defineOptions({
  name: "ClockSituationList"
});

// 响应式数据
const title = ref("上钟情况");
const loading = ref(false);
const tableRef = ref();
const selectedRows = ref([]);
const tabPosition = ref("day"); // 用于记录当前选中的时间范围
// 搜索表单
const searchForm = ref<ClockSituationParams>({});

// 技师列表
const employeeList = ref<Employee[]>([]);
const employeeOptions = computed(() => {
  return employeeList.value.map(emp => ({
    label: `${emp.t_name} (ID:${emp.t_id})`,
    value: emp.t_id
  }));
});

// 详情相关
const detailVisible = ref(false);
const detailLoading = ref(false);
const detailTableData = ref([]);
const currentRow = ref<ClockSituation | null>(null);
const detailPagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 表格数据
const tableData = ref([]);

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
  disabled: false,
  paginationSize: "default"
});

// 搜索字段配置
const searchFields = computed<SearchField[]>(() => [
  {
    prop: "jmid",
    label: "选择技师",
    type: "select",
    placeholder: "请选择技师",
    options: [...employeeOptions.value]
  },
  {
    prop: "start_date",
    label: "开始日期",
    type: "date",
    placeholder: "开始日期"
  },
  {
    prop: "end_date",
    label: "结束日期",
    type: "date",
    placeholder: "结束日期"
  }
]);
// 表格列配置
const columns: TableColumn[] = [
  {
    prop: "jmid",
    label: "技师ID",
    width: 100
  },
  {
    prop: "jdate",
    label: "上钟日期",
    width: 280,
    showOverflowTooltip: true
  },
  {
    prop: "jname",
    label: "技师名称",
    width: 180
  },
  {
    prop: "project_time",
    label: "时长",
    width: 140,
    align: "right"
  },
  {
    prop: "shouprice",
    label: "收款金额",
    width: 140,
    align: "right"
  },
  {
    prop: "tichengprice",
    label: "提成",
    width: 140,
    align: "right"
  },
  {
    prop: "gongsiprice",
    label: "公司剩余",
    width: 140,
    align: "right"
  },
  {
    label: "操作",
    fixed: "right",
    slot: "action"
  }
];

const handleGetEmployeeList = async () => {
  const response = await getEmployeeList({ status: 1 });
  if (response.code === 1) {
    employeeList.value = response.data.list;
  }
};

// 处理时间范围按钮点击
const handleTimeRangeClick = (type: "day" | "month") => {
  const today = new Date();
  let startDate: string;
  let endDate: string;

  if (type === "day") {
    // 当日：今天的开始到结束
    // const dateStr = today.toISOString().split("T")[0];
    startDate = "";
    endDate = "";
  } else if (type === "month") {
    // 本月至今：本月第一天到今天
    const year = today.getFullYear();
    const month = today.getMonth();
    startDate = `${year}-${String(month + 1).padStart(2, "0")}-01 00:00:00`;

    // 本月第一天
    // const firstDay = new Date(year, month, 1);
    // startDate = firstDay.toISOString().split("T")[0] + " 00:00:00";

    // 今天
    endDate = today.toISOString().split("T")[0] + " 23:59:59";
  }

  // 创建包含日期范围的搜索参数
  const searchParams = {
    start_date: startDate,
    end_date: endDate
  };

  handleSearch(searchParams, type);
};

// 事件处理
const handleSearch = (searchParams: any, timeType?: "day" | "month") => {
  console.log("搜索参数:", searchParams);
  console.log("当前 searchForm:", searchForm.value);
  console.log("时间类型:", timeType);

  if (timeType) {
    // 当点击时间范围按钮时，保留其他搜索条件，只更新日期
    const newSearchForm = {
      ...searchForm.value,
      ...searchParams
    };
    console.log("时间范围按钮 - 新的搜索表单:", newSearchForm);
    searchForm.value = newSearchForm;
  } else {
    // 当进行普通搜索时，处理日期格式
    const processedParams = { ...searchParams };

    // 如果传入的日期是 YYYY-MM-DD 格式，转换为带时间的格式
    if (
      processedParams.start_date &&
      processedParams.start_date.length === 10
    ) {
      processedParams.start_date = processedParams.start_date + " 00:00:00";
    }
    if (processedParams.end_date && processedParams.end_date.length === 10) {
      processedParams.end_date = processedParams.end_date + " 23:59:59";
    }

    // 如果传入的日期字段为空，但当前 searchForm 中有日期，则保留当前日期
    if (!processedParams.start_date && searchForm.value.start_date) {
      processedParams.start_date = searchForm.value.start_date;
    }
    if (!processedParams.end_date && searchForm.value.end_date) {
      processedParams.end_date = searchForm.value.end_date;
    }

    console.log("普通搜索 - 处理后的搜索表单:", processedParams);
    searchForm.value = processedParams;
  }

  pagination.current = 1;
  loadData();
};

const handleRefresh = () => {
  loadData();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadData();
};

const handleCurrentPageChange = (current: number) => {
  pagination.current = current;
  loadData();
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 查看详情
const handleViewDetail = (row: ClockSituation) => {
  if (!row.jmid) {
    ElMessage.warning("技师ID为空，无法查看详情");
    return;
  }
  currentRow.value = row;
  detailPagination.current = 1;
  detailPagination.size = 10;
  detailVisible.value = true;
  loadDetailData();
};

// 加载详情数据
const loadDetailData = async () => {
  if (!currentRow.value?.jmid) {
    ElMessage.error("技师ID为空");
    return;
  }

  detailLoading.value = true;

  try {
    const params: ClockSituationDetailParams = {
      jmid: currentRow.value.jmid,
      start_date: searchForm.value.start_date,
      end_date: searchForm.value.end_date,
      page: detailPagination.current.toString(),
      num: detailPagination.size.toString()
    };

    const response = await getClockSituationDetails(params);

    if (response.code === 1) {
      detailTableData.value = response.data.detailsarr || [];
      // API返回的total是字符串，需要转换为数字
      detailPagination.total = Number(response.data.total) || 0;
    } else {
      ElMessage.error(response.msg || "详情加载失败");
    }
  } catch (error) {
    console.error("详情加载错误:", error);
    ElMessage.error("详情加载失败");
  } finally {
    detailLoading.value = false;
  }
};

// 详情分页事件
const handleDetailSizeChange = (size: number) => {
  detailPagination.size = size;
  detailPagination.current = 1;
  loadDetailData();
};

const handleDetailCurrentChange = (current: number) => {
  detailPagination.current = current;
  loadDetailData();
};

// 详情汇总方法
const getDetailSummaries = (param: { columns: any[]; data: any[] }) => {
  const { columns, data } = param;
  const sums: string[] = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "";
      return;
    }
    if (index === 1) {
      sums[index] = "汇总：";
      return;
    }

    // 对数字列进行求和
    const values = data.map(item => Number(item[column.property]));
    if (!values.every(value => Number.isNaN(value))) {
      const total = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + value;
        } else {
          return prev;
        }
      }, 0);

      // 根据列类型格式化显示
      if (column.property === "project_time") {
        sums[index] = `${total}分钟`;
      } else if (
        column.property === "shouprice" ||
        column.property === "tichengprice"
      ) {
        sums[index] = total.toFixed(2);
      } else {
        sums[index] = total.toString();
      }
    } else {
      sums[index] = "";
    }
  });

  return sums;
};

// 表格汇总方法
const getSummaries = (param: { columns: any[]; data: any[] }) => {
  const { columns, data } = param;
  const sums: string[] = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      // 第一列显示空
      sums[index] = "";
      return;
    }
    if (index === 2) {
      // 第二列显示"汇总："
      sums[index] = "汇总：";
      return;
    }

    // 对数字列进行求和
    const values = data.map(item => Number(item[column.property]));
    if (!values.every(value => Number.isNaN(value))) {
      const total = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + value;
        } else {
          return prev;
        }
      }, 0);

      // 根据列类型格式化显示
      if (column.property === "project_time") {
        // 项目时长（分钟）
        sums[index] = `${total}分钟`;
      } else if (
        column.property === "shouprice" ||
        column.property === "tichengprice" ||
        column.property === "gongsiprice"
      ) {
        // 金额类（保留两位小数）
        sums[index] = `¥${total.toFixed(2)}`;
      } else {
        sums[index] = total.toString();
      }
    } else {
      sums[index] = "";
    }
  });

  return sums;
};

// 加载数据
const loadData = async () => {
  loading.value = true;

  try {
    const params: ClockSituationParams = {
      num: pagination.size.toString(),
      page: pagination.current.toString(),
      ...searchForm.value
    };

    // 尝试调用API
    try {
      const response = await getClockSituationList(params);

      if (response.code === 1) {
        tableData.value = response.data.list;
        title.value = response.data.title;
        // 上钟情况接口没有返回 total，使用 list 长度作为总数
        pagination.total = response.data.list.length;
        return;
      } else {
        ElMessage.error(response.msg || "数据加载失败");
      }
    } catch (apiError) {
      console.error("API调用错误:", apiError);
      ElMessage.error("数据加载失败，请稍后重试");
    }
  } catch (error) {
    console.error("数据加载错误:", error);
    ElMessage.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};

// 生命周期
onMounted(() => {
  // 默认加载当日上钟数据
  handleTimeRangeClick("day");
  handleGetEmployeeList();
});
</script>

<style scoped>
.member-management {
  height: 100%;
  background: #f5f7fa;
}
</style>
